#include <vector>

using namespace std;

/**
 * @brief 417. 太平洋大西洋水流问题
 * https://leetcode.cn/problems/pacific-atlantic-water-flow/
 */
class Solution {
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        int m = heights.size();
        int n = heights[0].size();

        vector<vector<bool>> pacific(m, vector<bool>(n, false));
        vector<vector<bool>> atlantic(m, vector<bool>(n, false));
        vector<vector<int>> result;

        for (int i=0; i<m; i++) {
            dfs(heights, pacific, i, 0);
            dfs(heights, atlantic, i, n-1);
        }

        for (int j=0; j<n; j++) {
            dfs(heights, pacific, 0, j);
            dfs(heights, atlantic, m-1, j);
        }

        for (int i=0; i<m; i++) {
            for (int j=0; j<n; j++) {
                if (pacific[i][j] && atlantic[i][j]) result.push_back(vector<int>{i,j});
            }
        }

        return result;
    }

    void dfs(vector<vector<int>>& heights, vector<vector<bool>>& ocean, int i, int j) {
        if (ocean[i][j]) return;
        ocean[i][j] = true;

        int m = heights.size();
        int n = heights[0].size();
        if (i-1>=0 && heights[i-1][j]>=heights[i][j]) dfs(heights, ocean, i-1, j);
        if (i+1<m  && heights[i+1][j]>=heights[i][j]) dfs(heights, ocean, i+1, j);
        if (j-1>=0 && heights[i][j-1]>=heights[i][j]) dfs(heights, ocean, i, j-1);
        if (j+1<n  && heights[i][j+1]>=heights[i][j]) dfs(heights, ocean, i, j+1);
    }
};
